package com.smsc.headend.connector.netty.encoder;

import com.smsc.headend.connector.builder.LoggerBuilder;
import com.smsc.headend.connector.netty.NettyConfigHelper;
import com.smsc.headend.connector.utils.LogFileNameUtil;
import com.smsc.headend.connector.utils.NetUtil;
import com.smsc.headend.module.asset.entity.ComEntity;
import com.smsc.headend.module.protocol.cosem.util.ByteUtils;
import com.smsc.headend.module.task.dto.ConnectorTask;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;

import static com.smsc.headend.connector.service.impl.DeviceConnectServiceImpl.CHANNEL;

public class AnsiEncoder extends MessageToByteEncoder<byte[]> {
    @Autowired
    LogFileNameUtil logFileNameUtil;

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, byte[] bytes, ByteBuf byteBuf) throws Exception {
        ComEntity com = channelHandlerContext.channel().attr(NettyConfigHelper.comEntityAttrKey).get();
        ConnectorTask connectorTask = channelHandlerContext.channel().attr(NettyConfigHelper.connectTaskRegular).get();
        MDC.put(CHANNEL, NetUtil.getIpFromChannel(channelHandlerContext.channel()));
        if (com == null) {
            LoggerBuilder.getLogger("anno-device", this.getClass()).info("-->:{}", ByteUtils.byteToHexString(bytes));
        } else if (com.getComId() == -1L) {
            LoggerBuilder.getLogger(com.getModuleSn(), this.getClass()).info("-->(anno):{}", ByteUtils.byteToHexString(bytes));
        } else {
            LoggerBuilder.getLogger(logFileNameUtil.getLogFileName(com), this.getClass()).info("-->:{}, {}", connectorTask.getTaskNo(), ByteUtils.byteToHexString(bytes));
        }
        byteBuf.writeBytes(bytes);
    }
}
